#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称: user_admin_enhanced_api.py
完整存储路径: backend/api/user_admin_enhanced_api.py
功能说明:
    增强版用户管理API接口，支持批量操作、高级筛选等功能。
    包括批量删除、批量角色分配、批量状态变更等操作。
    
使用说明:
    通过 Flask 蓝图实现，配合增强版前端用户管理界面使用。
"""
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from functools import wraps
from datetime import datetime, timedelta
from backend.models.user import User
from backend.models.system_log import SystemLog
from backend.infrastructure.database import db
from backend.models.role import Role
from backend.services.user_role_service import set_user_roles
from sqlalchemy import and_, or_

user_admin_enhanced_api = Blueprint('user_admin_enhanced_api', __name__)

# 管理员权限装饰器
def admin_required(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        from flask_jwt_extended import get_jwt
        claims = get_jwt()
        roles = claims.get('roles', [])
        if 'admin' not in roles:
            return jsonify({'success': False, 'message': '仅管理员可操作'}), 403
        return fn(*args, **kwargs)
    return wrapper

# 批量删除用户
@user_admin_enhanced_api.route('/users/batch_delete', methods=['POST'])
@jwt_required()
@admin_required
def batch_delete_users():
    """
    批量删除用户
    请求体格式: {"user_ids": [1, 2, 3]}
    """
    try:
        data = request.get_json()
        user_ids = data.get('user_ids', [])
        
        if not user_ids:
            return jsonify({"success": False, "message": "请选择要删除的用户", "data": None}), 400
        
        # 验证用户ID
        users = User.query.filter(User.id.in_(user_ids)).all()
        if len(users) != len(user_ids):
            return jsonify({"success": False, "message": "部分用户不存在", "data": None}), 400
        
        # 检查是否包含当前用户
        current_user_id = get_jwt_identity()
        if int(current_user_id) in user_ids:
            return jsonify({"success": False, "message": "不能删除当前登录用户", "data": None}), 400
        
        # 执行批量删除
        deleted_count = User.query.filter(User.id.in_(user_ids)).delete(synchronize_session=False)
        db.session.commit()
        
        # 记录系统日志
        current_user = User.query.get(current_user_id)
        operator = current_user.username if current_user else '未知用户'
        ip_address = request.remote_addr
        
        log = SystemLog(
            action='bulk_delete',
            table_name='users',
            record_id=None,
            operator=operator,
            description=f"批量删除了 {deleted_count} 个用户，ID: {user_ids}",
            ip_address=ip_address,
            created_at=datetime.now()
        )
        db.session.add(log)
        db.session.commit()
        
        return jsonify({
            "success": True,
            "message": f"成功删除 {deleted_count} 个用户",
            "data": {"deleted_count": deleted_count}
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            "success": False,
            "message": f"批量删除失败: {str(e)}",
            "data": None
        }), 500

# 批量分配角色
@user_admin_enhanced_api.route('/users/batch_assign_roles', methods=['POST'])
@jwt_required()
@admin_required
def batch_assign_roles():
    """
    批量分配角色
    请求体格式: {"user_ids": [1, 2, 3], "roles": ["teacher", "doctor"]}
    """
    try:
        data = request.get_json()
        user_ids = data.get('user_ids', [])
        role_names = data.get('roles', [])
        
        if not user_ids:
            return jsonify({"success": False, "message": "请选择要分配角色的用户", "data": None}), 400
        
        if not role_names:
            return jsonify({"success": False, "message": "请选择要分配的角色", "data": None}), 400
        
        # 验证用户存在
        users = User.query.filter(User.id.in_(user_ids)).all()
        if len(users) != len(user_ids):
            return jsonify({"success": False, "message": "部分用户不存在", "data": None}), 400
        
        # 验证角色存在
        roles = Role.query.filter(Role.name.in_(role_names)).all()
        if len(roles) != len(role_names):
            return jsonify({"success": False, "message": "部分角色不存在", "data": None}), 400
        
        role_ids = [role.id for role in roles]
        
        # 批量分配角色
        success_count = 0
        for user_id in user_ids:
            try:
                set_user_roles(user_id, role_ids)
                success_count += 1
            except Exception as e:
                print(f"为用户 {user_id} 分配角色失败: {str(e)}")
        
        db.session.commit()
        
        # 记录系统日志
        current_user_id = get_jwt_identity()
        current_user = User.query.get(current_user_id)
        operator = current_user.username if current_user else '未知用户'
        ip_address = request.remote_addr
        
        log = SystemLog(
            action='bulk_assign_roles',
            table_name='users',
            record_id=None,
            operator=operator,
            description=f"批量为 {success_count} 个用户分配角色: {role_names}，用户ID: {user_ids}",
            ip_address=ip_address,
            created_at=datetime.now()
        )
        db.session.add(log)
        db.session.commit()
        
        return jsonify({
            "success": True,
            "message": f"成功为 {success_count} 个用户分配角色",
            "data": {"success_count": success_count}
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            "success": False,
            "message": f"批量分配角色失败: {str(e)}",
            "data": None
        }), 500

# 批量更新状态
@user_admin_enhanced_api.route('/users/batch_update_status', methods=['POST'])
@jwt_required()
@admin_required
def batch_update_status():
    """
    批量更新用户状态
    请求体格式: {"user_ids": [1, 2, 3], "status": "suspended"}
    """
    try:
        data = request.get_json()
        user_ids = data.get('user_ids', [])
        new_status = data.get('status')
        
        if not user_ids:
            return jsonify({"success": False, "message": "请选择要更新状态的用户", "data": None}), 400
        
        if not new_status:
            return jsonify({"success": False, "message": "请指定新的状态", "data": None}), 400
        
        # 验证状态值
        valid_statuses = ['active', 'pending', 'suspended', 'blocked']
        if new_status not in valid_statuses:
            return jsonify({"success": False, "message": "无效的状态值", "data": None}), 400
        
        # 验证用户存在
        users = User.query.filter(User.id.in_(user_ids)).all()
        if len(users) != len(user_ids):
            return jsonify({"success": False, "message": "部分用户不存在", "data": None}), 400
        
        # 检查是否包含当前用户（如果要禁用状态）
        current_user_id = get_jwt_identity()
        if int(current_user_id) in user_ids and new_status in ['suspended', 'blocked']:
            return jsonify({"success": False, "message": "不能禁用当前登录用户", "data": None}), 400
        
        # 执行批量更新
        updated_count = User.query.filter(User.id.in_(user_ids)).update(
            {'status': new_status}, 
            synchronize_session=False
        )
        db.session.commit()
        
        # 记录系统日志
        current_user = User.query.get(current_user_id)
        operator = current_user.username if current_user else '未知用户'
        ip_address = request.remote_addr
        
        log = SystemLog(
            action='bulk_update_status',
            table_name='users',
            record_id=None,
            operator=operator,
            description=f"批量将 {updated_count} 个用户状态更新为 {new_status}，用户ID: {user_ids}",
            ip_address=ip_address,
            created_at=datetime.now()
        )
        db.session.add(log)
        db.session.commit()
        
        return jsonify({
            "success": True,
            "message": f"成功更新 {updated_count} 个用户状态",
            "data": {"updated_count": updated_count}
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            "success": False,
            "message": f"批量更新状态失败: {str(e)}",
            "data": None
        }), 500

# 高级用户查询（支持筛选和分页）
@user_admin_enhanced_api.route('/users/advanced', methods=['GET'])
@jwt_required()
@admin_required
def get_users_advanced():
    """
    高级用户查询，支持多种筛选条件和分页
    查询参数:
    - user_type: web/miniprogram
    - role: 角色名称
    - status: active/pending/suspended/blocked
    - search: 搜索关键词（用户名、真实姓名、手机、邮箱）
    - date_from: 创建时间起始日期 (YYYY-MM-DD)
    - date_to: 创建时间结束日期 (YYYY-MM-DD)
    - page: 页码
    - per_page: 每页数量
    """
    try:
        # 获取查询参数
        user_type = request.args.get('user_type')
        role_filter = request.args.get('role')
        status_filter = request.args.get('status')
        search_term = request.args.get('search', '').strip()
        date_from = request.args.get('date_from')
        date_to = request.args.get('date_to')
        page = int(request.args.get('page', 1))
        per_page = int(request.args.get('per_page', 10))
        
        # 构建查询
        query = User.query
        
        # 用户类型筛选
        if user_type:
            query = query.filter(User.user_type == user_type)
        
        # 状态筛选
        if status_filter:
            query = query.filter(User.status == status_filter)
        
        # 搜索条件
        if search_term:
            search_pattern = f"%{search_term}%"
            query = query.filter(or_(
                User.username.like(search_pattern),
                User.real_name.like(search_pattern),
                User.mobile.like(search_pattern),
                User.email.like(search_pattern),
                User.department.like(search_pattern),
                User.position.like(search_pattern)
            ))
        
        # 日期范围筛选
        if date_from:
            try:
                date_from_obj = datetime.strptime(date_from, '%Y-%m-%d')
                query = query.filter(User.created_at >= date_from_obj)
            except ValueError:
                pass
        
        if date_to:
            try:
                date_to_obj = datetime.strptime(date_to, '%Y-%m-%d')
                # 包含整个结束日期
                date_to_obj = date_to_obj.replace(hour=23, minute=59, second=59)
                query = query.filter(User.created_at <= date_to_obj)
            except ValueError:
                pass
        
        # 分页查询
        pagination = query.order_by(User.created_at.desc()).paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
        
        users = pagination.items
        users_list = []
        
        for user in users:
            user_dict = user.to_dict()
            
            # 如果有角色筛选，只返回匹配的用户
            if role_filter:
                user_roles = user_dict.get('roles', [])
                if role_filter not in user_roles:
                    continue
            
            users_list.append(user_dict)
        
        return jsonify({
            "success": True,
            "message": "获取用户列表成功",
            "data": {
                "users": users_list,
                "pagination": {
                    "page": page,
                    "per_page": per_page,
                    "total": pagination.total,
                    "pages": pagination.pages,
                    "has_prev": pagination.has_prev,
                    "has_next": pagination.has_next
                }
            }
        }), 200
        
    except Exception as e:
        return jsonify({
            "success": False,
            "message": f"获取用户列表失败: {str(e)}",
            "data": None
        }), 500

# 获取用户统计信息
@user_admin_enhanced_api.route('/users/stats', methods=['GET'])
@jwt_required()
@admin_required
def get_user_stats():
    """
    获取用户统计信息
    """
    try:
        # 总用户数
        total_users = User.query.count()
        
        # 按状态统计
        active_users = User.query.filter_by(status='active').count()
        pending_users = User.query.filter_by(status='pending').count()
        suspended_users = User.query.filter_by(status='suspended').count()
        blocked_users = User.query.filter_by(status='blocked').count()
        
        # 按用户类型统计
        web_users = User.query.filter_by(user_type='web').count()
        miniprogram_users = User.query.filter_by(user_type='miniprogram').count()
        
        # 按角色统计
        role_stats = []
        roles = Role.query.all()
        for role in roles:
            user_count = User.query.join(User.roles).filter(Role.id == role.id).count()
            role_stats.append({
                "role_name": role.name,
                "user_count": user_count
            })
        
        # 最近注册用户（7天内）
        seven_days_ago = datetime.now() - timedelta(days=7)
        recent_users = User.query.filter(User.created_at >= seven_days_ago).count()
        
        return jsonify({
            "success": True,
            "message": "获取用户统计成功",
            "data": {
                "total_users": total_users,
                "status_stats": {
                    "active": active_users,
                    "pending": pending_users,
                    "suspended": suspended_users,
                    "blocked": blocked_users
                },
                "type_stats": {
                    "web": web_users,
                    "miniprogram": miniprogram_users
                },
                "role_stats": role_stats,
                "recent_users": recent_users
            }
        }), 200
        
    except Exception as e:
        return jsonify({
            "success": False,
            "message": f"获取用户统计失败: {str(e)}",
            "data": None
        }), 500

# 导出用户数据
@user_admin_enhanced_api.route('/users/export', methods=['GET'])
@jwt_required()
@admin_required
def export_users():
    """
    导出用户数据（CSV格式）
    支持与高级查询相同的筛选参数
    """
    try:
        import csv
        import io
        from flask import make_response
        
        # 获取查询参数（与高级查询相同）
        user_type = request.args.get('user_type')
        role_filter = request.args.get('role')
        status_filter = request.args.get('status')
        search_term = request.args.get('search', '').strip()
        date_from = request.args.get('date_from')
        date_to = request.args.get('date_to')
        
        # 构建查询（与高级查询相同逻辑）
        query = User.query
        
        if user_type:
            query = query.filter(User.user_type == user_type)
        
        if status_filter:
            query = query.filter(User.status == status_filter)
        
        if search_term:
            search_pattern = f"%{search_term}%"
            query = query.filter(or_(
                User.username.like(search_pattern),
                User.real_name.like(search_pattern),
                User.mobile.like(search_pattern),
                User.email.like(search_pattern)
            ))
        
        if date_from:
            try:
                date_from_obj = datetime.strptime(date_from, '%Y-%m-%d')
                query = query.filter(User.created_at >= date_from_obj)
            except ValueError:
                pass
        
        if date_to:
            try:
                date_to_obj = datetime.strptime(date_to, '%Y-%m-%d')
                date_to_obj = date_to_obj.replace(hour=23, minute=59, second=59)
                query = query.filter(User.created_at <= date_to_obj)
            except ValueError:
                pass
        
        # 获取所有匹配的用户
        users = query.order_by(User.created_at.desc()).all()
        
        # 角色筛选（在Python中处理）
        if role_filter:
            filtered_users = []
            for user in users:
                user_roles = [role.name for role in user.roles]
                if role_filter in user_roles:
                    filtered_users.append(user)
            users = filtered_users
        
        # 创建CSV数据
        output = io.StringIO()
        writer = csv.writer(output)
        
        # 写入表头
        writer.writerow([
            '用户ID', '用户名', '真实姓名', '手机号', '邮箱', 
            '性别', '部门', '职位', '用户类型', '状态', 
            '角色', '创建时间', '备注'
        ])
        
        # 写入数据
        for user in users:
            roles_str = ', '.join([role.name for role in user.roles])
            writer.writerow([
                user.id,
                user.username or '',
                user.real_name or '',
                user.mobile or '',
                user.email or '',
                user.gender or '',
                user.department or '',
                user.position or '',
                '小程序' if user.user_type == 'miniprogram' else 'PC端',
                user.status or '',
                roles_str,
                user.created_at.strftime('%Y-%m-%d %H:%M:%S') if user.created_at else '',
                user.remark or ''
            ])
        
        # 创建响应
        output.seek(0)
        response = make_response(output.getvalue())
        response.headers['Content-Type'] = 'text/csv; charset=utf-8'
        response.headers['Content-Disposition'] = f'attachment; filename=users_export_{datetime.now().strftime("%Y%m%d_%H%M%S")}.csv'
        
        # 记录导出操作日志
        current_user_id = get_jwt_identity()
        current_user = User.query.get(current_user_id)
        operator = current_user.username if current_user else '未知用户'
        ip_address = request.remote_addr
        
        log = SystemLog(
            action='export_users',
            table_name='users',
            record_id=None,
            operator=operator,
            description=f"导出了 {len(users)} 个用户的数据",
            ip_address=ip_address,
            created_at=datetime.now()
        )
        db.session.add(log)
        db.session.commit()
        
        return response
        
    except Exception as e:
        return jsonify({
            "success": False,
            "message": f"导出用户数据失败: {str(e)}",
            "data": None
        }), 500
